//
//  ImageProvider.swift
//  Tiktok
//
//  Created by xmd on 11/2/20.
//

import Foundation
import UIKit
import Combine

class ImageProvider : ObservableObject {
    @Published var uiImages: [String: UIImage] = [:]
    static var cancellables: [String: AnyCancellable] = [:]
    
    func get(from url: String) -> UIImage? {
        let key = url
        if ImageProvider.cancellables[key] == nil {
            ImageProvider.cancellables[key] =
                URLSession.shared.dataTaskPublisher(for: URL(string: url)!)
                .map { data, urlResponse in UIImage(data: data) }
                .receive(on: DispatchQueue.main)
                .replaceError(with: nil)
                .assign(to: \.uiImages[key], on: self)
        }
        return uiImages[key]
    }
}
